package com.javaking.clanteam.hvz.utils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.javaking.clanteam.hvz.R;

public class BarcodeScanActivity extends Activity {

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // This may be getting called form a subclass and we need to have an option where
        // it doesn't call the setup functions.
        if (savedInstanceState!=null && savedInstanceState.getBoolean("ignore", false))
        	return;
        setContentView(R.layout.scan);
        setTitle(R.string.scanOrInput);
    }

	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch(requestCode)
		{
		case IntentIntegrator.REQUEST_CODE: // Was a scan result
			// parse the scan result
	    	IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
	    	if(scanResult != null) // ensure result is not null
	    	{
	    		// Set the result to the barcode and finish
		    	Intent activityResult = new Intent();
		    	activityResult.putExtra("barcode", scanResult.getContents());
		    	setResult(RESULT_OK, activityResult);
		    	finish();
	    	}
	    	break;
		}
    }
    
    /**
     * Scan barcode.
     */
    public void scanBarcode(View v)
    {
    	new IntentIntegrator(this).initiateScan();
    }
    
    /**
     * Manually type in a barcode
     */
    public void manualKey(View v)
    {
    	// Hide the original views and show the new ones.
    	findViewById(R.id.manualBarcodeLayout).setVisibility(View.VISIBLE);
		findViewById(R.id.scan_buttonLayout).setVisibility(View.GONE);
		
		// Get the edit text and 
		EditText manualBarcodeEdit = (EditText)findViewById(R.id.manualBarcodeEdit);
		manualBarcodeEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(actionId==EditorInfo.IME_NULL||actionId==EditorInfo.IME_ACTION_DONE)
				{
					Bundle bundle = new Bundle();
					bundle.putString("barcode", v.getText().toString());
					Intent resultData = new Intent();
					resultData.putExtras(bundle);
					setResult(Activity.RESULT_OK, resultData);
					finish();
					return true;
				}
				return false;
			}
		});
    }

}
